<?php defined('SYSPATH') or die('No direct script access.');

class MyOrganization_Controller extends OrgController {

    private static $DISPLAY_PATH = 'org/myOrganization/display';

    public $DISPLAY_REP_LIST_UUID = 'org/myOrganization/display/repList';

    public function __construct() {
        parent::__construct();
        $this->activeMenuItem = OrgMenu::$ORGANIZATION;
    }

    /**
     * Default action method.
     */
    public function display() {
        $id = $this->getAuthOrg('id');
        $this->viewData['organization'] = $this->getAuthOrg();
        
        if ($this->getSessionData()->getAuthOrgRole() == auth::$ORG_ROLE_ORGANIZER) {
            $this->viewData['memberList'] = $this->dao->orderedOrgMembers($id, $this->DISPLAY_PERSON_LIST_UUID);
            $this->viewData['addRepAcValues'] = $this->dao->optionsOrganizationRepCandidate($id);
            $this->viewData['representativeList'] = $this->dao->orderedOrgRepresentatives($id, $this->DISPLAY_REP_LIST_UUID);
        }

        $this->renderSubview('org/myOrganization/myOrganizationDisplay');
    }
    
    private function validatePersonId($personId) {
        if ($this->getSessionData()->getAuthOrgRole() != auth::$ORG_ROLE_ORGANIZER) {
            $this->msg->error('auth.accessDenied-operation');
            $this->redirect(self::$DISPLAY_PATH);
        }
        
        if (! valid::isId($personId)) {
            $this->msg->error('error.invalidId');
            $this->redirect(self::$DISPLAY_PATH);
        }

        $person = $this->dao->fetchPersonById($personId);
        if (! $person) {
            $this->msg->error('error.recordNotFound');
            $this->redirect(self::$DISPLAY_PATH);
        }
        return $person;
    }
    
    public function addRepresentative() {
        $person = $this->validatePersonId($this->input->post('person_id'));
        $this->dao->insert('organization_rep', 
                array(
                    'person_id' => $person['id'], 
                    'organization_id' => $this->getAuthOrg('id')
                )
        );

        $this->msg->info('organization.addRepSuccess', format::personFullName($person));
        $this->redirect('org/myOrganization/display');
    }
    
    public function removeRepresentative() {
        $person = $this->validatePersonId($this->input->get('person_id'));

        $this->dao->executeQuery(
                'DELETE FROM organization_rep WHERE person_id = :person_id AND organization_id = :organization_id',
                array('person_id' => $person['id'], 'organization_id' => $this->getAuthOrg('id')));

        $this->msg->info('organization.removeRepSuccess', format::personFullName($person));
        $this->redirect('org/myOrganization/display');
    }

    public function edit() {
        $this->loadFormData();
        $this->viewData['organization'] = $this->getAuthOrg();
        $this->renderSubview('org/myOrganization/myOrganizationEdit');
    }

    protected function loadFormData() {
        $this->viewData['countryOptions'] = $this->dao->optionsCountry();
    }

    function save() {
        $organization = $this->postToDbValues();
        $id = $organization['id'];
        $this->viewData['organization'] = $organization;
        
        // Basic validation
        $validator = new EntityValidator($organization, 'organization', $this->msg);
        $validator->required('name');
        $validator->boolean('emails_enabled');
        $validator->required('country_code');
        $validator->applicationLanguage('preferred_language');
        if ($this->msg->hasErrors()) {
            $this->loadFormData();
            $this->renderSubview('org/myOrganization/myOrganizationEdit');
            return;
        }

        // Database validation
        if ($this->dao->alreadyExists('organization', 'name', $organization)) {
            $this->msg->error('organization.error-alreadyExists-name');
        }
        if ($this->msg->hasErrors()) {
            $this->loadFormData();
            $this->renderSubview('org/myOrganization/myOrganizationEdit');
            return;
        }

        // DB Update
        $this->dao->update('organization', $organization);
        $this->msg->info('organization.editSuccess', $organization['name']);

        $this->redirect(self::$DISPLAY_PATH);
    }
}
